package com.yicong.ants.manager.ad;

import android.app.Activity;
import android.content.Context;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.cchao.simplelib.Const;
import com.cchao.simplelib.LibCore;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseActivity;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.EnergyHelper;
import com.yicong.ants.ui.find.YcWebViewActivity;
import com.yicong.ants.utils.ToastUtils;
import com.yicong.ants.viewmodel.AppStartViewModel;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.listener.BaseZxBannerListener;
import com.zx.sdk.listener.BaseZxRewardListener;
import com.zx.sdk.listener.BaseZxShortVideoListener;
import com.zx.sdk.listener.BaseZxSplashListener;
import com.zx.sdk.model.SuspensionInfo;
import com.zx.sdk.model.ZxError;
import com.zx.sdk.util.ConfigHelper;
import com.zx.sdk.util.RunnableHelper;
import com.zx.sdk.util.ToastHelper;
import com.zx.sdk.view.widget.BaseNewsAdView;

import java.util.Map;

public class AdManager {
    private static boolean preloading = false;//通过listener回调记录是否正在加载中

    public enum State {
        SHOWN, DISMISSED, COMPLETE, CLICKED
    }

    public static void preloadAndShowSplash(Activity activity, ViewGroup container) {
        if (BuildConfig.STORE) {// 如果是市场上架包则不显示广告
            return;
        }
        final String mobPid = activity.getString(R.string.splash_pid);
        BaseZxSplashListener listener = new BaseZxSplashListener() {
            @Override
            public void onADClicked() {
                AppStartViewModel.setAdState(State.CLICKED);
            }

            @Override
            public void onADDismissed() {
                AppStartViewModel.setAdState(State.DISMISSED);
            }

            @Override
            public void onADExposure() {
                AppStartViewModel.setAdState(State.SHOWN);
            }

            @Override
            public void onADLoaded(long l) {
            }

            @Override
            public void onADPresent() {

            }

            @Override
            public void onADTick(long l) {

            }

            @Override
            public void onNoAD(ZxError adError) {
                switch (adError.getErrorCode()) {
                    case ZxError.NO_AD_FINAL:
                        RxBus.get().postEvent(Constants.Event.NO_AD_FINAL);
                        break;
                    case ZxError.NO_LEAGUE_MEMBER:
                        ToastHelper.showToast("广告加载错误，请检查配置！");
                        break;
                }
            }

            @Override
            public void onPreloading() {

            }

            @Override
            public void onLoaded() {

            }

            @Override
            public void onPreLoadNoAD(ZxError adError) {

            }

            @Override
            public void onDownloadTipsDialogShow() {

            }

            @Override
            public void onDownloadTipsDialogDismiss() {

            }

            @Override
            public void onDownloadTipsDialogCancel() {

            }
        };
        ZxSDK.preloadAdv(activity, ZxSDK.SPLASH, mobPid, container, listener);
        RunnableHelper.postDelay((long) (ConfigHelper.getSplashWaitSec() * 1000F), () -> {
            if (activity.isDestroyed()) {
                return;
            }
            ZxSDK.showTargetAndBidding(activity, mobPid, ZxSDK.SPLASH, container, listener);
        });
    }

    public static void preloadRewardOnly(Activity activity, int eventCode) {
        ZxSDK.preloadAdv(activity, ZxSDK.REWARD, activity.getString(R.string.reward_pid), null, new ZxRewardListener(activity, eventCode, true, true));
    }

    public static void preloadInterstitialOnly(Activity activity) {
        ZxSDK.preloadAdv(activity, ZxSDK.INTERSTITIAL, activity.getString(R.string.interstitial_pid), null, new ZxRewardListener(activity, -999, true, false));
    }

    public static void preloadAndShowReward(Activity activity, int eventCode) {
        if (preloading) {
            ToastUtils.showLong(activity, "广告资源还在准备中,请稍后重试!");
            return;
        }
        ToastUtils.showLong(activity, "开始准备广告资源");
        ZxSDK.preloadAdv(activity, ZxSDK.REWARD, activity.getString(R.string.reward_pid), null, new ZxRewardListener(activity, eventCode, false, true));
    }

    public static void preloadAndShowInterstitial(Activity activity) {
        ZxSDK.preloadAdv(activity, ZxSDK.INTERSTITIAL, activity.getString(R.string.interstitial_pid), null, new ZxRewardListener(activity, -999, false, false));
    }

    public static void showReward(Activity activity, int eventCode) {
        if (preloading) {
            ToastUtils.showLong(activity, "广告资源还在准备中,请稍后重试!");
            return;
        }
        ToastUtils.showLong(activity, "开始加载广告");
        ZxSDK.showTargetAndBidding(activity, activity.getString(R.string.reward_pid), ZxSDK.REWARD, null, new ZxRewardListener(activity, eventCode, false, true));
    }

    public static void showInterstitial(Activity activity) {
        ZxSDK.showTargetAndBidding(activity, activity.getString(R.string.interstitial_pid), ZxSDK.INTERSTITIAL, null, new ZxRewardListener(activity, -999, false, false));
    }

    public static void destroyBanner(Activity activity) {
//        ZxSDK.destroyBanner(activity, pid);
    }

    public static class ZxRewardListener extends BaseZxRewardListener {
        private final int eventCode;
        private final Activity mActivity;
        private final boolean preLoadOnly;
        private final boolean isReward;

        ZxRewardListener(Activity activity, int eventCode, boolean preLoadOnly, boolean isReward) {
            this.eventCode = eventCode;
            this.mActivity = activity;
            this.preLoadOnly = preLoadOnly;
            this.isReward = isReward;
        }

        @Override
        public void onADClick() {
        }

        @Override
        public void onADClose() {
        }

        @Override
        public void onADExpose() {
        }

        @Override
        public void onADLoad() {
        }

        @Override
        public void onReward(@NonNull Map<String, Object> map) {
            RxBus.get().postEvent(eventCode, map);
        }

        @Override
        public void onVideoCached() {
        }

        @Override
        public void onVideoComplete() {
        }

        @Override
        public void onRewardStepVerify(int taskType, int currentTaskStatus) {

        }

        @Override
        public void onAdSkip(float v) {

        }

        @Override
        public void onPreLoadADError(ZxError error) {
        }

        @Override
        public void onVideoPlayError(ZxError error) {
            UiHelper.showToast("激励视频广告播放出错,请重试");
        }

        @Override
        public void onNoAD(ZxError error) {
            if (preLoadOnly) return;
            switch (error.getErrorCode()) {
                case ZxError.NO_AD_FINAL:
                    RxBus.get().postEvent(Constants.Event.NO_AD_FINAL);
                    break;
                case ZxError.NO_LEAGUE_MEMBER:
                    ToastHelper.showToast("广告加载错误，请检查配置！");
                    break;
            }
        }

        @Override
        public void onPreloading() {
            preloading = true;
        }

        @Override
        public void onLoaded() {
            preloading = false;
            if (!preLoadOnly) {
                if (isReward) {
                    showReward(mActivity, eventCode);
                } else {
                    showInterstitial(mActivity);
                }
            }
        }
    }

    static BaseZxBannerListener bannerListener = new BaseZxBannerListener() {
        @Override
        public void onNoAD(ZxError error) {

        }

        @Override
        public void onPreloading() {

        }

        @Override
        public void onLoaded() {

        }

        @Override
        public void onAdReady(Object object) {

        }

        @Override
        public void onAdShow(Object object) {

        }

        @Override
        public void onAdClick(Object object) {
            if (object instanceof SuspensionInfo) {
                Router.turnTo(ActivityUtils.getTopActivity(), YcWebViewActivity.class)
                        .putExtra(Const.Extra.Web_View_Url, ((SuspensionInfo) object).url)
                        .putExtra(Const.Extra.Web_View_Title_Visible, false)
                        .start();
            }
        }

        @Override
        public void onAdFailed(ZxError error) {

        }

        @Override
        public void onAdSwitch() {

        }

        @Override
        public void onAdClose(Object object) {

        }
    };

    public static void showBanner(Activity activity, ViewGroup container) {
        if (BuildConfig.STORE) {
            return;
        }
        String pid = activity.getString(R.string.user_info_banner_pid);
        ZxSDK.preloadAdv(activity, ZxSDK.BANNER, pid, container, bannerListener);
        ThreadUtils.runOnUiThreadDelayed(() -> ZxSDK.showTargetAndBidding(activity, pid, ZxSDK.BANNER, container, bannerListener), 2000);
    }

    public static void showSuspension(Activity activity, ViewGroup container) {
        if (BuildConfig.STORE) {
            return;
        }
        String pid = activity.getString(R.string.suspension_pid);
        ZxSDK.preloadAdv(activity, ZxSDK.SUSPENSION, pid, container, bannerListener);
        ThreadUtils.runOnUiThreadDelayed(() -> ZxSDK.showTargetAndBidding(activity, pid, ZxSDK.SUSPENSION, container, bannerListener), 2000);
    }

    public static Fragment getShortVideoFragment() {
        Fragment[] fragmentContainer = new Fragment[1];
        fragmentContainer[0] = ZxSDK.getShortVideoFragment(LibCore.getContext().getString(R.string.short_video_pid), new BaseZxShortVideoListener() {

            @Override
            public void onPageEnter() {
                AppHelper.mShortVideoTimes--;
                Logs.d("ksContentPage onPageEnter " + AppHelper.mShortVideoTimes);
                if (AppHelper.mShortVideoTimes == 0) {
                    EnergyHelper.doneEnergyTask((BaseActivity) fragmentContainer[0].getActivity());
                }
            }

            @Override
            public void onPageResume() {

            }

            @Override
            public void onPagePause() {

            }

            @Override
            public void onPageLeave() {

            }
        });
        return fragmentContainer[0];
    }

    public static BaseNewsAdView getNewsView(Context context) {
        return ZxSDK.getNewsView(context, LibCore.getContext().getString(R.string.news_pid));
    }
}
